package com.sophie.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 操作cookie的帮助类
 */
public class CookieUtil {
    /**
     * 向客户端浏览器中存入cookie值
     *
     * @param name     属性名
     * @param value    属性值
     * @param request  请求对象
     * @param response 响应对象
     */
    public static void setCookie(String name, String value, HttpServletRequest request, HttpServletResponse response) {
        //1.创建Cookie对象(cookie只能存储String类型的数据)
        Cookie cookie = new Cookie(name, value);
        //2.设置Cookie保存路径
        cookie.setPath(request.getContextPath() + "/");
        //3.设置存活时间(账号信息保存一周) 秒
        cookie.setMaxAge(60 * 60 * 24 * 7);
        //4.将cookie存入客户端的浏览器中
        response.addCookie(cookie);
    }

    /**
     * 删除浏览器中cookie值
     *
     * @param name
     * @param request
     * @param response
     */
    public static void removeCookie(String name, HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    //删除值
                    cookie.setValue("");
                    cookie.setPath(request.getContextPath() + "/");
                    // 0通知浏览器立即删除这个Cookie
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                    return;
                }
            }
        }
    }

    /**
     * 根据属性名，获取对应的cookie值
     *
     * @param name
     * @param request
     * @param response
     * @return
     */
    public static String getCookieValue(String name, HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        //说明浏览器中没有这cookie
        return null;
    }

}
